package fastjson;

import com.alibaba.fastjson.JSON;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.TimeValue;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.Map;

@BenchmarkMode(Mode.AverageTime)
@State(Scope.Thread)
public class URLEncodeVSBase64URL {
    
    Map<String, Object> map;
    
    @Setup
    public void setup() {
        map = Tool.buildMap();
    }
    
    @Benchmark
    public void toJSONString(){
        String string = JSON.toJSONString(map);
    }
    @Benchmark
    public void toJSONStringURLEncode() throws UnsupportedEncodingException {
        URLEncoder.encode(JSON.toJSONString(map), "UTF-8");
    }
    
    @Benchmark
    public void toJSONBytes(){
        JSON.toJSONBytes(map);
    }
    @Benchmark
    public void toJSONBytesBase64URL() throws UnsupportedEncodingException {
        Base64.getUrlEncoder().encode(JSON.toJSONBytes(map));
    }
    
    
    public static void main(String[] args) throws RunnerException {
        
        Options opt = new OptionsBuilder()
                .include(URLEncodeVSBase64URL.class.getSimpleName())
                .forks(2)
                .threads(3)
                .warmupIterations(2)
                .measurementIterations(3)
                .warmupTime(TimeValue.seconds(10))
                .measurementTime(TimeValue.seconds(10))
                .build();
        
        
        new Runner(opt).run();
    }
}
